//
//  UserInformationViewController.m
//  quxiangtao
//
//  Created by xbmios on 2018/7/23.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "UserInformationViewController.h"
#import "NickNameChangedViewController.h"
#import "PhoneValidViewController.h"

#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

#import "NSString+Base64.h"
#import "NSData+Base64.h"

@interface UserInformationViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (strong, nonatomic) UIView *iconView;
@property (strong, nonatomic) UILabel *iconL;
@property (strong, nonatomic) UIImageView *iconIV;
@property (strong, nonatomic) UIImageView *rightArrow1;

@property (strong, nonatomic) UIView *nickNameView;
@property (strong, nonatomic) UILabel *nickNameL;
@property (strong, nonatomic) UILabel *nickName;
@property (strong, nonatomic) UIImageView *rightArrow2;

@property (strong, nonatomic) UIView *phoneView;
@property (strong, nonatomic) UILabel *phoneL;
@property (strong, nonatomic) UILabel *phone;
@property (strong, nonatomic) UIImageView *rightArrow3;


@property (strong, nonatomic) UIImagePickerController *pickerVC;

@end

@implementation UserInformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = WhiteColor;
    self.title = @"用户资料";
    
    [self createUI];

}
#pragma mark -修改头像
- (void)changeIcon:(UIGestureRecognizer *)recognizer {
    
    NSLog(@"修改头像");
    
    // 先判断是否登录
    
    [LEEActionSheet actionSheet].custom.config.LeeCustomCancelButton(^(UIButton *button){
        
        [button setTitle:@"取消" forState:UIControlStateNormal];
        //GoldColor
        [button setTitleColor:Colorff4200 forState:UIControlStateNormal];
        
    }).LeeAddCustomButton(^(UIButton *button){
        
        [button setTitle:@"拍照" forState:UIControlStateNormal];
        [button setTitleColor:Color333333 forState:UIControlStateNormal];
        [button addTarget:self action:@selector(cameraClick) forControlEvents:UIControlEventTouchUpInside];
        
    })  .LeeAddCustomButton(^(UIButton *button){
        
        [button setTitle:@"选一张照片" forState:UIControlStateNormal];
        [button setTitleColor:Color333333 forState:UIControlStateNormal];
        [button addTarget:self action:@selector(photoClick) forControlEvents:UIControlEventTouchUpInside];
        
    }) .LeeShowFromViewController(self);
}

- (void)cameraClick {
    
    //判断是否可以打开相机，模拟器此功能无法使用
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
        
    }else{
        //如果没有提示用户
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"你没有摄像头" delegate:nil cancelButtonTitle:@"确定!" otherButtonTitles:nil];
        [alert show];
        
    }
    
    
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    
    if(authStatus ==AVAuthorizationStatusRestricted){
        
        NSLog(@"Restricted");
        
    }else if(authStatus == AVAuthorizationStatusDenied){
        
        NSLog(@"Denied");     //应该是这个，如果不允许的话
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"请在设备的\"设置-隐私-相机\"中允许访问相机。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        
        return;
        
    }
    
    else if(authStatus == AVAuthorizationStatusAuthorized){//允许访问
        
        //        NSLog(@"Authorized");
        
    }else if(authStatus == AVAuthorizationStatusNotDetermined){
        
        [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
            if(granted){//点击允许访问时调用
                //用户明确许可与否，媒体需要捕获，但用户尚未授予或拒绝许可。
                NSLog(@"Granted access to %@", mediaType);
            }
            else {
                NSLog(@"Not granted access to %@", mediaType);
                return ;
            }
            
        }];
        
    }else {
        
        NSLog(@"Unknown authorization status");
        
    }
    
}

- (void)photoClick {
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    
    self.pickerVC = picker;
    
    //相册是可以用模拟器打开的
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        //打开相册选择照片
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:picker animated:YES completion:^{
            
            UIViewController *vc = picker.viewControllers.lastObject;
            UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] init];
            backBtn.title = @"取消";
            [backBtn setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor], NSFontAttributeName:Font(30)} forState:UIControlStateNormal];
            
            backBtn.target = self;
            backBtn.action = @selector(cancelBtnClick:);
            
            vc.navigationItem.rightBarButtonItem = backBtn;
            
        }];
        
        
    }else{
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"你没有摄像头" delegate:nil cancelButtonTitle:@"确定!" otherButtonTitles:nil];
        [alert show];
        
    }
    
}

- (void)cancelBtnClick:(UIBarButtonItem *)btn {
    
    [self.pickerVC dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark -选择照片代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *image = info[UIImagePickerControllerEditedImage];
    
    NSData *data = UIImageJPEGRepresentation(image, 0.01f);
    NSString *base64EncodedString = [NSString base64StringFromData:data length:[data length]];

    if (data == nil) {
        
        [[KYAlertView sharedInstance] showAlertViewWithMessage:@"请上传正式格式的图片！"];
        
        return;
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
//    NSString *param = [NSString stringWithFormat:@"{\"user_id\":\"%@\",\"user_photo\":\"%@\"}", [RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey], [RSA encryptString:base64EncodedString publicKey:PublicKey]];
    
    NSString *param = [NSString stringWithFormat:@"{\"user_id\":\"%@\",\"user_photo\":\"%@\"}", [RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey], base64EncodedString];
    
    [PPNetworkHelper POST:@"user/User/Updateuserphoto" parameters:@{@"json" : param} success:^(id responseObject) {
        
        NSLog(@"修改头像：%@",responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            self.iconIV.image = image;
            
            [CommonUserInfo sharedInstance].photoUrl = [NSString stringWithFormat:@"%@", responseObject[@"data"][@"user_photo"]];
            
//            NSData *photo = [NSData base64DataFromString:responseObject[@"data"][@"user_photo"]];
            
//            UIImage *image = [UIImage imageWithData:photo];
//
//            [CommonUserInfo sharedInstance].iconIV = image;
            
        }else {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
            
        }
        
    } failure:^(NSError *error) {
        
        if (error) {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
       
        }
        
    }];
    
}



#pragma mark -修改昵称
- (void)nickNameChangeClick:(UIGestureRecognizer *)recognizer {
    
    NickNameChangedViewController *vc = [[NickNameChangedViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];

}

#pragma mark -手机号修改
- (void)phoneViewClick:(UIGestureRecognizer *)recognizer {
    
    PhoneValidViewController *vc = [[PhoneValidViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)createUI {
    
    [self.view addSubview:self.iconView];
    [self.iconView addSubview:self.iconL];
    [self.iconView addSubview:self.iconIV];
    [self.iconView addSubview:self.rightArrow1];
    
    [self.view addSubview:self.nickNameView];
    [self.nickNameView addSubview:self.nickNameL];
    [self.nickNameView addSubview:self.nickName];
    [self.nickNameView addSubview:self.rightArrow2];

    [self.view addSubview:self.phoneView];
    [self.phoneView addSubview:self.phoneL];
    [self.phoneView addSubview:self.phone];
    [self.phoneView addSubview:self.rightArrow3];
    
    
    __weak typeof(self) weakSelf = self;
    [self.iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.view.mas_top);
        make.height.mas_equalTo(jisuan(86));
    }];
    [self.iconL mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.iconView.mas_left).with.offset(jisuan(40));
        make.centerY.mas_equalTo(weakSelf.iconView.mas_centerY);
        
    }];
    [self.rightArrow1 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.mas_equalTo(weakSelf.iconView.mas_right).with.offset(-jisuan(40));
        make.centerY.mas_equalTo(weakSelf.iconView.mas_centerY);
        make.width.mas_equalTo(jisuan(12));
        make.height.mas_equalTo(jisuan(20));
    }];
    [self.iconIV mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.mas_equalTo(weakSelf.iconView.mas_centerY);
        make.right.mas_equalTo(weakSelf.rightArrow1.mas_left).with.offset(-jisuan(60));
        make.width.mas_equalTo(jisuan(60));
        make.height.mas_equalTo(jisuan(60));
        
    }];
    
    [self.nickNameView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.iconView.mas_bottom);
        make.height.mas_equalTo(jisuan(74));
        
    }];
    [self.nickNameL mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.nickNameView.mas_left).with.offset(jisuan(40));
        make.centerY.mas_equalTo(weakSelf.nickNameView.mas_centerY);
        
    }];
    [self.rightArrow2 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.mas_equalTo(weakSelf.nickNameView.mas_right).with.offset(-jisuan(40));
        make.centerY.mas_equalTo(weakSelf.nickNameView.mas_centerY);
        make.width.mas_equalTo(jisuan(12));
        make.height.mas_equalTo(jisuan(20));
    }];
    [self.nickName mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.mas_equalTo(weakSelf.nickNameView.mas_centerY);
        make.right.mas_equalTo(weakSelf.rightArrow2.mas_left).with.offset(-jisuan(40));
        
    }];
    
    [self.phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.nickNameView.mas_bottom);
        make.height.mas_equalTo(jisuan(74));
        
    }];
    [self.phoneL mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.phoneView.mas_left).with.offset(jisuan(40));
        make.centerY.mas_equalTo(weakSelf.phoneView.mas_centerY);
        
    }];
    [self.rightArrow3 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.mas_equalTo(weakSelf.phoneView.mas_right).with.offset(-jisuan(40));
        make.centerY.mas_equalTo(weakSelf.phoneView.mas_centerY);
        make.width.mas_equalTo(jisuan(12));
        make.height.mas_equalTo(jisuan(20));
    }];
    [self.phone mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.mas_equalTo(weakSelf.phoneView.mas_centerY);
        make.right.mas_equalTo(weakSelf.rightArrow3.mas_left).with.offset(-jisuan(40));
        
    }];
}

#pragma mark -lazy
- (UIView *)iconView {
    
    if (!_iconView) {
        
        _iconView = [[UIView alloc] init];
        _iconView.backgroundColor = WhiteColor;
        
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeIcon:)];
        [_iconView addGestureRecognizer:recognizer];
    }

    return _iconView;
}
- (UILabel *)iconL {
    
    if (!_iconL) {
        
        _iconL = [[UILabel alloc] init];
        _iconL.text = @"头像";
        _iconL.textColor = Color333333;
        _iconL.font = Font(24);
        _iconL.textAlignment = NSTextAlignmentLeft;
        
    }
    return _iconL;
}
- (UIImageView *)iconIV {
    
    if (!_iconIV) {
        
        _iconIV = [[UIImageView alloc] init];
        _iconIV.contentMode = UIViewContentModeScaleAspectFill;
//        _iconIV.image = [UIImage imageNamed:@"userInformationbg"];
        
        _iconIV.layer.cornerRadius = jisuan(30);
        _iconIV.layer.masksToBounds = YES;
        
    }
    
    return _iconIV;
}

- (UIImageView *)rightArrow1 {
    
    if (!_rightArrow1) {
        
        _rightArrow1 = [[UIImageView alloc] init];
        _rightArrow1.contentMode = UIViewContentModeScaleAspectFit;
        _rightArrow1.image = [UIImage imageNamed:@"rightArrowBG"];
    
    }
    
    return _rightArrow1;
}

- (UIView *)nickNameView {
    
    if (!_nickNameView) {
        
        _nickNameView = [[UIView alloc] init];
        _nickNameView.backgroundColor = WhiteColor;
        
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(nickNameChangeClick:)];
        [_nickNameView addGestureRecognizer:recognizer];
    }
    
    return _nickNameView;
}
- (UILabel *)nickNameL {
    
    if (!_nickNameL) {
        
        _nickNameL = [[UILabel alloc] init];
        _nickNameL.text = @"昵称";
        _nickNameL.textColor = Color333333;
        _nickNameL.font = Font(24);
        _nickNameL.textAlignment = NSTextAlignmentLeft;
        
    }
    return _nickNameL;
}
- (UILabel *)nickName {
    
    if (!_nickName) {
        
        _nickName = [[UILabel alloc] init];
//        _nickName.text = @"何生枷锁";
        _nickName.textColor = Color999999;
        _nickName.font = Font(24);
        _nickName.textAlignment = NSTextAlignmentRight;
        
    }
    
    return _nickName;
}

- (UIImageView *)rightArrow2 {
    
    if (!_rightArrow2) {
        
        _rightArrow2 = [[UIImageView alloc] init];
        _rightArrow2.contentMode = UIViewContentModeScaleAspectFit;
        _rightArrow2.image = [UIImage imageNamed:@"rightArrowBG"];
        
    }
    
    return _rightArrow2;
}
- (UIView *)phoneView {
    
    if (!_phoneView) {
        
        _phoneView = [[UIView alloc] init];
        _phoneView.backgroundColor = WhiteColor;
        
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(phoneViewClick:)];
        [_phoneView addGestureRecognizer:recognizer];
        
    }
    
    return _phoneView;
}
- (UILabel *)phoneL {
    
    if (!_phoneL) {
        
        _phoneL = [[UILabel alloc] init];
        _phoneL.text = @"手机号";
        _phoneL.textColor = Color333333;
        _phoneL.font = Font(24);
        _phoneL.textAlignment = NSTextAlignmentLeft;
        
    }
    return _phoneL;
}
- (UILabel *)phone {
    
    if (!_phone) {
        
        _phone = [[UILabel alloc] init];
//        _phone.text = @"150****2333";
        _phone.textColor = Color999999;
        _phone.font = Font(24);
        _phone.textAlignment = NSTextAlignmentRight;
        
    }
    
    return _phone;
}

- (UIImageView *)rightArrow3 {
    
    if (!_rightArrow3) {
        
        _rightArrow3 = [[UIImageView alloc] init];
        _rightArrow3.contentMode = UIViewContentModeScaleAspectFit;
        _rightArrow3.image = [UIImage imageNamed:@"rightArrowBG"];
        
    }
    
    return _rightArrow3;
}

#pragma mark -设置
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
//    self.tabBarController.tabBar.hidden = YES;
    
    
    self.phone.text = [CommonUserInfo sharedInstance].phone;
    self.nickName.text = [CommonUserInfo sharedInstance].nickName;
    
    
//    self.iconIV.image = [CommonUserInfo sharedInstance].iconIV;
    
    if ([CommonUserInfo sharedInstance].photoUrl.length <= 0) {

        self.iconIV.image = [UIImage imageNamed:@"userInformationbg"];
//        self.iconIV.image = [UIImage imageNamed:@"iconHeader"];

    }else {

        [self.iconIV sd_setImageWithURL:[NSURL URLWithString:[CommonUserInfo sharedInstance].photoUrl]];

//        self.iconIV.image = [CommonUserInfo sharedInstance].iconIV;
    }
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
//    self.navigationController.navigationBar.hidden = NO;
//    self.tabBarController.tabBar.hidden = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
